import { OSS_DOMAIN, OSS_REGION } from "../constants";
import OSS from "ali-oss";
import { IStsToken, lastInvitation } from "../interfaces";
import { useRef, useEffect, useCallback } from "react";

export * from "./axios";
export * from "./upload-file";
export * from "./encrypt-utils";

const documentTypes = {
  word: [
    ".doc",
    ".docm",
    ".docx",
    ".docxf",
    ".dot",
    ".dotm",
    ".dotx",
    ".epub",
    ".fodt",
    ".fb2",
    ".htm",
    ".html",
    ".mht",
    ".odt",
    ".oform",
    ".ott",
    ".oxps",
    ".pdf",
    ".rtf",
    ".txt",
    ".djvu",
    ".xml",
    ".xps",
  ],
  cell: [
    ".csv",
    ".fods",
    ".ods",
    ".ots",
    ".xls",
    ".xlsm",
    ".xlsx",
    ".xlt",
    ".xltm",
    ".xltx",
  ],
  slide: [
    ".fodp",
    ".odp",
    ".otp",
    ".pot",
    ".potm",
    ".potx",
    ".pps",
    ".ppsm",
    ".ppsx",
    ".ppt",
    ".pptm",
    ".pptx",
  ],
};
/** 筛选得到文件类型 */
export const filterDocumentType = (extensionName) => {
  const keys = Object.keys(documentTypes);
  for (let i = 0; i < keys.length; i++) {
    const values = documentTypes[keys[i]];
    if (values.indexOf(extensionName) !== -1) {
      return keys[i];
    }
  }
  return "word";
};

export type storeKey =
  | "token"
  | "priRsaKey"
  | "pubRsaKey"
  | "userInfo"
  | "inviteLink";

/** 本地存储 */
export const setStore = (key: storeKey, value: string) => {
  localStorage.setItem(key, value);
};
export const getStore = (key: storeKey) => {
  return localStorage.getItem(key);
};
export const delStore = (key: storeKey) => {
  return localStorage.removeItem(key);
};

/** 拼接oss地址 */
export const getOssUrl = ({
  bucketName,
  path,
}: {
  bucketName: string;
  path: string;
}) => {
  return `https://${bucketName}.${OSS_DOMAIN}/${path}`;
};

/** 保存最近一次邀请信息 */
export const setLastInvitation = (invitation: lastInvitation) => {
  const _invitation = getLastInvitation();
  const newInvitation = {
    ..._invitation,
    ...invitation,
    type: Object.keys(invitation)[0] || "project",
  };
  localStorage.setItem("lastInvitation", JSON.stringify(newInvitation));
};

export const getLastInvitation = (): undefined | lastInvitation => {
  const str = localStorage.getItem("lastInvitation") || "";
  try {
    return JSON.parse(str);
  } catch (e) {
    return;
  }
};

/** 获取文件大小描述 */
export const getFileSizeText = (size: number) => {
  if (!size) return "0";
  if (size < 1024) {
    return `${size}B`;
  }
  const k = (size / 1024).toFixed(2);
  if (parseFloat(k) < 1024) {
    return `${k}KB`;
  }
  const m = (size / 1024 / 1024).toFixed(2);
  if (parseFloat(m) < 1024) {
    return `${m}MB`;
  }
  const g = (size / 1024 / 1024 / 1024).toFixed(2);
  if (parseFloat(g) < 1024) {
    return `${g}GB`;
  }
  return `${g}GB`;
};

export const getOssThumbnail = ({
  bucketName,
  path,
}: {
  bucketName: string;
  path: string;
}) => {
  const str = localStorage.getItem("stsToken") || "";
  let stsToken: IStsToken | null = null;
  try {
    stsToken = JSON.parse(str) as IStsToken;
  } catch (e) {}
  if (!stsToken) return "";
  const client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: OSS_REGION,
    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    accessKeyId: stsToken.accessKeyId,
    accessKeySecret: stsToken.accessKeySecret,
    // 从STS服务获取的安全令牌（SecurityToken）。
    stsToken: stsToken.securityToken,
    // 填写Bucket名称。
    bucket: bucketName,
  });
  // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
  const filename = path; // 自定义下载后的文件名。
  const response = {
    "content-disposition": `attachment; filename=${encodeURIComponent(
      filename
    )}`,
  };
  // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
  const url = client.signatureUrl(path, { response });
  return url;
};
const blaskColorMap = {
  "#ECEEF2": "#262626",
  "#DCC6FF": "#262626",
  "#BACEFD": "#262626",
  "#B1E8FC": "#262626",
  "#A9EFE6": "#262626",
  "#C6FCC0": "#262626",
  "#DFEE96": "#262626",
  "#F8E6AB": "#262626",
  "#FDD4A4": "#262626",
  "#FBBFBC": "#262626",
  "#F9AED9": "#262626",
  "#CED1D8": "#262626",
  "#AD82F7": "#262626",
  "#82A7FC": "#262626",
  "#7EDAFB": "#262626",
  "#64E8D6": "#262626",
  "#99EB90": "#262626",
  "#C9E053": "#262626",
  "#FFDD72": "#262626",
  "#FFB861": "#262626",
  "#FF7B76": "#262626",
  "#FF90CF": "#262626",
  "#fff": "#262626",
  "#FFFFFF": "#262626",
};

const whiteColorMap = {
  "#8A909F": "#ffffff",
  "#7F3AF5": "#ffffff",
  "#3972F9": "#ffffff",
  "#269FD7": "#ffffff",
  "#26B49C": "#ffffff",
  "#6BC950": "#ffffff",
  "#B3D600": "#ffffff",
  "#FCC60A": "#ffffff",
  "#FB8802": "#ffffff",
  "#F54A45": "#ffffff",
  "#F14BA9": "#ffffff",
  "#262626": "#ffffff",
  "#4E1BA7": "#ffffff",
  "#1C4CBA": "#ffffff",
  "#1C7EAA": "#ffffff",
  "#198373": "#ffffff",
  "#237B19": "#ffffff",
  "#667900": "#ffffff",
  "#AA7804": "#ffffff",
  "#B26206": "#ffffff",
  "#AC2E28": "#ffffff",
  "#9E1460": "#ffffff",
};

/** 字体颜色表 */
export const textColorMap: Record<string, string> = {
  ...blaskColorMap,
  ...whiteColorMap,
};

export const scrollToCenter = () => {
  const menuDom = document?.querySelector(".tabs-menu") as HTMLElement;
  const curTabDom = document?.querySelector(
    ".tabs-menu .active"
  ) as HTMLElement;

  const menuWidth = menuDom?.clientWidth;
  const curTabOffsetLeft = curTabDom?.offsetLeft;
  const boxWidth = document?.querySelector(".tabs")?.clientWidth as number;
  if (curTabOffsetLeft < boxWidth / 2) {
    menuDom?.scrollTo(0, 0);
  } else {
    menuDom?.scrollTo(
      curTabOffsetLeft - boxWidth / 2 + curTabDom?.offsetWidth / 2,
      0
    );
  }
};

export const isIos = () => {
  return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);
};

export function useDebounce(fn, delay, dep = []) {
  const { current } = useRef({ fn, timer: null });
  useEffect(
    function () {
      current.fn = fn;
    },
    [fn]
  );

  return useCallback(function f(...args) {
    if (current.timer) {
      clearTimeout(current.timer);
    }
    current.timer = setTimeout(() => {
      current.fn.call(this, ...args);
    }, delay);
  }, dep);
}
